package com.kly.sc.api.application.controller.pay;

import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.api.Response;
import com.kly.sc.api.application.controller.pay.request.GooglePayDto;
import com.kly.sc.api.application.controller.pay.response.PayResultResponse;
import com.kly.sc.api.application.controller.user.response.UserLikeResponse;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.application.service.utils.BaseComponent;
import com.kly.sc.api.application.utils.Result;
import com.kly.sc.api.infras.utils.StringUtils;
import com.kly.user.service.UserMsgService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 支付相关处理类
 * @author linqu
 */
@RestController
@RequestMapping("api/apy")
public class PayController extends BaseComponent {

    @Resource
    RedisClient redisClient;

    @Resource
    UserMsgService userMsgService;

    /**
     * 查询支付状态
     */
    private final static String ORDER_KEY = "userCode_{}_productId_{}_orderId_{}";
    @RequestMapping("/queryPayStatus")
    public Response queryPayStatus(@Valid @RequestBody GooglePayDto googlePayDto) {
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();


//        ProductDto productDto = getProductDto(product);

        String productId=googlePayDto.getProductId();
        String orderId=googlePayDto.getOrderId();
        String purchaseToken=googlePayDto.getPurchaseToken();
        String email="lkc@gmail.com";

        String token = redisClient.get(ORDER_KEY, userCode, productId, orderId);
        if (StringUtils.isNotEmpty(token)) {
            // 1: 支付处理中
            return Response.ok(PayResultResponse.builder().status(1).build());
        }
        // TODO: 2023/6/19 调用支付项目的支付接口，获取最终的支付结果
        return Response.ok();
    }


    /**
     * 用于支付项目的回调，处理回调结果信息
     */
    @RequestMapping("/payCallback")
    public Response payCallback(@Valid @RequestBody GooglePayDto googlePayDto) {

        // TODO: 2023/6/19 1）接收支付项目发起的回调
        // TODO: 2023/6/19 2) 根据支付回调结果，更新订单状态，并生成权益

        return Response.ok();

    }


    @PostMapping("/payFail")
    @ApiOperation(value = "支付失败", notes = "支付失败")
    public Result payFail() {
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        userMsgService.sendFailPayMessage(userCode);
        return Result.ok();
    }


}
